/*
 * 上海远境文化传媒有限公司 版权所有
 */
package facade.vo.base;

import models.base.AdminMenu;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 用户值对象.
 */
public class MenuVO implements Serializable {

    private static final long serialVersionUID = -8908366898420430708L;

    public String id;

    /**
     * 所在文件夹名
     */
    public String name;

    /**
     * 模块名称
     */
    public String title;

    public String code;

    public String jump;

    public Integer sort;
    /**
     * icon
     */
    public String icon;

    public List<MenuVO> list;

    public static List<MenuVO> from(List<AdminMenu> menuList){
        if(menuList == null || menuList.size() == 0) return Collections.emptyList();
        List<MenuVO> voList = set("0",menuList);

        for (MenuVO menu : voList) {
            List<MenuVO> subBusinessList = set(menu.id,menuList);
            menu.list = subBusinessList;
        }
        return voList;
    }

    private static List<MenuVO> set(String parentId,List<AdminMenu> menuList){
        if(StringUtils.isEmpty(parentId) || menuList == null || menuList.size() == 0) return Collections.emptyList();
        List<MenuVO> voList = new ArrayList<>();
        for (AdminMenu adminMenu : menuList) {
            if(parentId.equals(adminMenu.parentId)){
                MenuVO menuItem = new MenuVO();
                menuItem.id     = adminMenu.getId();
                menuItem.code   = adminMenu.code;
                menuItem.name   = adminMenu.name;
                menuItem.title  = adminMenu.title;
                menuItem.icon   = adminMenu.icon;
                menuItem.jump    = adminMenu.url;
                menuItem.sort   = adminMenu.showOrder;
                voList.add(menuItem);
            }
        }

        Collections.sort(voList, new Comparator<MenuVO>() {
            @Override
            public int compare(MenuVO o1, MenuVO o2) {
                if(o1.sort != o2.sort) {
                    return o1.sort - o2.sort;
                }else{
                    return o1.code.compareTo( o2.code );
                }
            }
        });
        return voList;
    }
}
